

#include <stdio.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "iot_pwm.h"
#include "iot_errno.h"
#include "hi_io.h"

// 7-0
// 8-1

#define IOT_PWM_DUTY_MAX 100
#define PWM_FREQ_DIVITION 64000
#define DELAY_US 250000
#define STACK_SIZE (4096)
#define PWM_PORT_RED 2
#define PWM_PORT_GREEN 1
#define PWM_PORT_BLUE 0
#define DOUBLE (2)
#define CYCLE_COUNT 3

/* 初始化LED GPIO和PWM */
static void InitLedPwm(int pin, int pwmPort)
{
    // 初始化GPIO
    IoTGpioInit(pin);
    IoTGpioSetDir(pin, IOT_GPIO_DIR_OUT);
    
    // 设置GPIO为PWM功能
    hi_io_set_func(pin, 5);  // 5表示PWM功能
    // 初始化PWM
    IoTPwmInit(pwmPort);
}

static void PWMLedDemoTask(void)
{
    static int g_count = CYCLE_COUNT;

    while (g_count) {

        InitLedPwm(2,2);
        for (int i = 1; i < IOT_PWM_DUTY_MAX; i *= DOUBLE) {
            IoTPwmStart(PWM_PORT_RED, i, PWM_FREQ_DIVITION);
            usleep(DELAY_US);
        }
        for (int i = IOT_PWM_DUTY_MAX; i > 1; i /= DOUBLE) {
            IoTPwmStart(PWM_PORT_RED, i, PWM_FREQ_DIVITION);
            usleep(DELAY_US);
        }
        IoTPwmStop(PWM_PORT_RED);

        InitLedPwm(8,1);
        // 绿色呼吸
        printf("Green LED breathing...\n");
        for (int i = 1; i < IOT_PWM_DUTY_MAX; i *= DOUBLE) {
            IoTPwmStart(PWM_PORT_GREEN, i, PWM_FREQ_DIVITION);
            usleep(DELAY_US);
        }
        for (int i = IOT_PWM_DUTY_MAX; i > 1; i /= DOUBLE) {
            IoTPwmStart(PWM_PORT_GREEN, i, PWM_FREQ_DIVITION);
            usleep(DELAY_US);
        }
        IoTPwmStop(PWM_PORT_GREEN);

        InitLedPwm(7,0);
        for (int i = 1; i < IOT_PWM_DUTY_MAX; i *= DOUBLE) {
            IoTPwmStart(PWM_PORT_BLUE, i, PWM_FREQ_DIVITION);
            usleep(DELAY_US);
        }
        for (int i = IOT_PWM_DUTY_MAX; i > 1; i /= DOUBLE) {
            IoTPwmStart(PWM_PORT_BLUE, i, PWM_FREQ_DIVITION);
            usleep(DELAY_US);
        }
        IoTPwmStop(PWM_PORT_BLUE);

        g_count--;
    }
}

static void PWMLedDemo(void)
{
    osThreadAttr_t attr;

    attr.name = "PWMLedDemoTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = STACK_SIZE;
    attr.priority = osPriorityNormal;

    if (osThreadNew(PWMLedDemoTask, NULL, &attr) == NULL) {
        printf("[ColorfulLightDemo] Failed to create PWMLedDemoTask!\n");
    }
}

APP_FEATURE_INIT(PWMLedDemo);
